/**
 * Filename: UpLoadActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/10 15:37
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.UploadAdapter;
import com.github.postsanf.yinian.bean.YNUpList;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.db.DBManager;
import com.github.postsanf.yinian.db.YNUpProgress;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.WrapContentLinearLayoutManager;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 上传进度
 */
public class UpLoadActivity extends BaseActivity implements ISkinUpdate {
    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private List<YNUpList> upListData = new ArrayList<YNUpList>();
    private DBManager dbManager;
    private UploadAdapter mAdapter;
    private ProgressDialog mProgressDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_upload);
        BaseApplication.getInstance().mActivitys.add(this);
        registerReceiver();
        dbManager = new DBManager(this);
        initView();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.upload_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        mRecyclerView = (RecyclerView) findViewById(R.id.upload_recyclerview);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        mAdapter = new UploadAdapter(this, upListData);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemViewCacheSize(10);
        initData();
        boolean bb = getIntent().getBooleanExtra(ACTIONs.IstoSetWifi, false);
        if (bb) {
            ToSetWifiDialog();
        }
    }

    public void ToSetWifiDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否去设置WiFi");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("去设置");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            }
        });
    }

    private void initData() {
        boolean isCancel;
        List<YNUpProgress> upProgresses = dbManager.queryUpProgressAll();
        for (int i = 0; i < upProgresses.size(); i++) {
            long uped = dbManager.getUpedSizeById(upProgresses.get(i).id);
            long divi = Long.parseLong(upProgresses.get(i).upsize) == 0 ? 1 : Long.parseLong(upProgresses.get(i).upsize);
            int percent = (int) (uped * 100 / divi);
            isCancel = (1 == upProgresses.get(i).upstatus) ? true : false;
            upListData.add(new YNUpList(upProgresses.get(i).id, upProgresses.get(i).upfirstimg, upProgresses.get(i).uptime, upProgresses.get(i).upgname, percent, uped, upProgresses.get(i).upsize, isCancel));
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void noticeServiceUp(int id) {
        Intent mIntent = new Intent(UpLoadActivity.this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionDeleteUp);
        mIntent.putExtra(ACTIONs.aCancelId, id);
        startService(mIntent);
    }

    private void deleteList(int id) {
        for (int i = 0; i < upListData.size(); i++) {
            if (upListData.get(i).getUpid() == id) {
                upListData.remove(i);
                mAdapter.notifyDataSetChanged();
                if (upListData.size() == 0) {
                    finish();
                }
                return;
            }
        }
    }

    // 进度更新广播接收器
    private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTIONs.actionUpdateProgress:
                    int upId = intent.getIntExtra(ACTIONs.aUpId, 0);
                    int upProgress = intent.getIntExtra(ACTIONs.aUpProgress, 0);
                    long upSized = intent.getLongExtra(ACTIONs.aUpSized, 0);
                    String upSpeed = intent.getStringExtra(ACTIONs.aUpSpeed);
                    handleResult(upId, upProgress, upSized, upSpeed);
                    break;
                case ACTIONs.actionDeleteList:
                    int deleteid = intent.getIntExtra(ACTIONs.aCancelId, 0);
                    deleteList(deleteid);
                    break;
                case "uploadstartPd":
                    mProgressDialog = ProgressDialog.show(UpLoadActivity.this, "", "");
                    break;
                case "uploadoverPd":
                    if (mProgressDialog != null) {
                        mProgressDialog.dismiss();
                    }
                    break;
            }
        }
    };


    // 同步更新上传进度条
    private void handleResult(int upid, int upprogress, long upsized, String upSpeed) {
        for (int i = 0; i < upListData.size(); i++) {
            if (upListData.get(i).getUpid() == upid) {
                upListData.get(i).setUpsize(upsized);
                upListData.get(i).setUppercent(upprogress);
                if (100 <= upprogress) {
                    upListData.get(i).setUpSpeed("0.00 KB/s");
                    upListData.get(i).setUpsize(Long.parseLong(upListData.get(i).getUpTotalSize()));
//                    noticeServiceUp(upid);
                } else {
                    upListData.get(i).setUpSpeed(upSpeed);
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    // 注册广播接收器
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTIONs.actionUpdateProgress);
        filter.addAction(ACTIONs.actionDeleteList);
        filter.addAction("uploadstartPd");
        filter.addAction("uploadoverPd");
        registerReceiver(uploadImgReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放数据库资源
        // dbManager.closeDB();
        BaseApplication.getInstance().mActivitys.remove(this);
        unregisterReceiver(uploadImgReceiver);
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", CommonConstants.THEME_DRAWABLE, CommonConstants.THEME_PACKAGE)));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", CommonConstants.THEME_COLOR, CommonConstants.THEME_PACKAGE)));
                mAdapter.setSource(mResource);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
